const OptimizeCssPlugin = require('optimize-css-assets-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const webpackMerger = require('webpack-merge');
const chalk = require('chalk');
const baseConfig = require('./webpack.base');
const { srcDir, publicPath } = require('./path');
const { dllReferPlugins } = require('./utils');
const theme = require('./theme');

const prodConfig = {
  mode: 'production',

  stats: {
    children: false,
    // 过滤MiniCssExtractPlugin打包时由于css引入顺序引发的警告
    warningsFilter: warning => /Conflicting order between/gm.test(warning),
  },

  output: {
    filename: 'js/[name].[contenthash:8].js',
    chunkFilename: 'js/[name].[contenthash:8].js',
    publicPath,
  },

  devtool: false,

  module: {
    rules: [
      {
        test: /\.css$/,
        exclude: /node_modules/,
        include: srcDir,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: { importLoaders: 1 },
          },
          'postcss-loader',
        ],
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        include: srcDir,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: { importLoaders: 2 },
          },
          'postcss-loader',
          'sass-loader',
        ],
      },
      {
        test: /\.less$/,
        include: /node_modules\/antd/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'postcss-loader',
          {
            loader: 'less-loader',
            options: { modifyVars: theme, javascriptEnabled: true },
          },
        ],
      },
    ],
  },

  optimization: {
    minimizer: [
      new TerserPlugin({
        cache: true, // 利用缓存
        parallel: true, // 开启多线程
        terserOptions: {
          compress: {
            drop_console: true, // 丢弃console
          },
          output: {
            beautify: false,
          },
        },
      }),
      new OptimizeCssPlugin({}),
    ],
  },

  plugins: [
    new BundleAnalyzerPlugin(),
    new ProgressBarPlugin({
      format: `  ${chalk.magenta.bold('build [:bar] ')}${chalk.green.bold(' :percent ')}${chalk.blue.bold('(:elapsed seconds)')}`,
      clear: false,
    }),
    new MiniCssExtractPlugin({
      filename: 'css/[name].[contenthash:8].css',
      chunkFilename: 'css/[name].[contenthash:8].css',
    }),
    ...dllReferPlugins(),
  ],
};

module.exports = webpackMerger(baseConfig, prodConfig);
